const { Model, DataTypes } = require('sequelize');
const sequelize = require('../db/db');
const Question = require('./Question');
const QuestionSetExercise = require('./QuestionSetExercise');

class QuestionSetAnswer extends Model {}

QuestionSetAnswer.init(
  {
    id: {
      type: DataTypes.CHAR(18),
      primaryKey: true,
      allowNull: false,
      comment: '答题记录ID'
    },
    exercise_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '练习ID',
      references: {
        model: QuestionSetExercise,
        key: 'id'
      }
    },
    question_id: {
      type: DataTypes.CHAR(18),
      allowNull: false,
      comment: '题目ID',
      references: {
        model: Question,
        key: 'id'
      }
    },
    answer: {
      type: DataTypes.CHAR(1),
      allowNull: true,
      comment: '用户答案'
    },
    is_correct: {
      type: DataTypes.TINYINT,
      allowNull: true,
      comment: '是否正确：0-错误，1-正确'
    },
    answer_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '答题时间'
    }
  },
  {
    sequelize,
    modelName: 'QuestionSetAnswer',
    tableName: 'question_set_answer',
    timestamps: false,
    indexes: [
      {
        fields: ['exercise_id']
      },
      {
        fields: ['question_id']
      }
    ]
  }
);

// 建立与QuestionSetExercise的关联关系
QuestionSetAnswer.belongsTo(QuestionSetExercise, {
  foreignKey: 'exercise_id',
  targetKey: 'id',
  as: 'exercise'
});

// 建立与Question的关联关系
QuestionSetAnswer.belongsTo(Question, {
  foreignKey: 'question_id',
  targetKey: 'id',
  as: 'question'
});

// 在QuestionSetExercise和Question模型中添加关联
setTimeout(() => {
  // 练习与答题记录的关联
  if (QuestionSetExercise.hasMany) {
    QuestionSetExercise.hasMany(QuestionSetAnswer, {
      foreignKey: 'exercise_id',
      sourceKey: 'id',
      as: 'answers'
    });
  }

  // 题目与答题记录的关联
  if (Question.hasMany) {
    Question.hasMany(QuestionSetAnswer, {
      foreignKey: 'question_id',
      sourceKey: 'id',
      as: 'setAnswers'
    });
  }
}, 0);

module.exports = QuestionSetAnswer; 